package tripx.system;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * <p>
 * <code><b>Logger</b></code> make import role to monitor the system. It prints
 * import information to console or file.
 * </p>
 * <p>
 * You can invoke {@link #setMode(int)} to change the output.
 * <code><b>CONSOLE_MODE</b></code> and <code><b>FILE_MODE</b></code> are
 * available.
 * </p>
 * 
 * @author zhb
 * 
 */
public class Logger {

	private static Logger logger;

	/**
	 * the constant specify the output which is directed to the console
	 */
	public static int CONSOLE_MODE = 0;
	/**
	 * the constant specify the output which is directed to the file
	 */
	public static int FILE_MODE = 1;

	private int mode;

	private FileWriter writer;

	private Logger() {
		File logFile = new File("./log.txt");
		if (!logFile.exists()) {
			// create the log file
			try {
				logFile.createNewFile();
				writer = new FileWriter(logFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static Logger getInstance() {
		if (logger == null) {
			logger = new Logger();
		}
		return logger;
	}

	/**
	 * set up the log mode, CONSOLE_MODE or FILE_MDOE
	 * 
	 * @param mode
	 */
	public void setMode(int mode) {
		this.mode = mode;
	}

	/**
	 * write the information message
	 * 
	 * @param message
	 */
	public void info(String message) {
		String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
				.format(Calendar.getInstance().getTime());
		if (mode == CONSOLE_MODE) {
			System.out.println(timeStamp + ": " + message);
		} else {
			try {
				writer.write("---Info---:" + timeStamp + ": " + message + "\n");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * write the error message
	 * 
	 * @param message
	 */
	public void err(String message) {
		String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
				.format(Calendar.getInstance().getTime());
		if (mode == CONSOLE_MODE) {
			System.err.println(timeStamp + ": " + message);
		} else {
			try {
				writer.write("***Err***:" + timeStamp + ": " + message + "\n");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * necessary clean up
	 */
	public void close() {
		try {
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
